<template>
	<s-layout navbar="custom">
		<view class="container">
			<image mode="scaleToFill" src="https://xmcang.weihankeji.com/static/back.png" class="bg-img"></image>
			<image class="bg-img-mi" src="https://xmcang.weihankeji.com/static/backImg.png" mode=""></image>
			<!-- 小米仓标题 -->
			<image @tap="toHome" class="back" src="https://xmcang.weihankeji.com/static/backBtn.png" alt="" />
			<view class="title">请按照小米仓顺序来点击图片</view>
			<!-- 任务按钮 -->
			<view class="task-image">
				<block v-for="(task, index) in shuffledTasks" :key="index">
					<image :style="getButtonStyle(index)" :src="task.imageUrl"
						:class="{ completed: task.completed, disabled: task.disabled }" class="task-image"
						@click="completeTask(index)"></image>
				</block>
			</view>

			<!-- 显示抽奖按钮 -->
			<!-- <button v-if="canDraw" class="lottery-button" @click="openLotteryModal">
			开始抽奖
		</button> -->

			<view v-if="canDraw" class="modal">
				<image src="https://www.xiaomicang.com/static/red.png" class="red" @click="openLottery"></image>
			</view>
			<view class="modal" v-if="lotteryResult">
				<img src="https://www.xiaomicang.com/static/zhong.png" class="banner" alt="" />
				<view class="result-modal">
					<view class="result-content">
						<view class="result-text-wrapper">
							<view class="result-text">恭喜您抽中了</view>
							<view class="result">{{ lotteryResult[0].name }}</view>
						</view>
						<image :src="lotteryResult[0].imageUrl" mode="aspectFill" class="result-image" />
						<view class="result-bottom">请在“中奖记录”查看已获得奖品</view>
						<button class="close-button" @click="closeLotteryResult(lotteryResult[0].name)">确定</button>
					</view>
				</view>
				<img @click="closeLotteryResult(lotteryResult[0].name)" class="close"
					src="https://www.xiaomicang.com/static/close.png" alt="" />
			</view>
			<!-- 抽奖结果弹窗 -->
		</view>
	</s-layout>
</template>

<script>
	import sheep from "@/sheep";
	import {
		computed
	} from 'vue';
	import {
		staticUrl
	} from '@/sheep/config';
	import {
		showShareModal,
		showAuthModal
	} from '@/sheep/hooks/useModal';
	export default {
		data() {
			return {
				authType: "accountLogin",
				tasks: [{
						id: 0,
						completed: false,
						disabled: false,
						name: "小",
						imageUrl: "https://www.xiaomicang.com/static/cang1_active.png",
						completedImageUrl: "https://www.xiaomicang.com/static/cang1.png"

					},
					{
						id: 1,
						completed: false,
						disabled: false,
						name: "米",
						imageUrl: "https://www.xiaomicang.com/static/cang2_active.png",
						completedImageUrl: "https://www.xiaomicang.com/static/cang2.png"
					},
					{
						id: 2,
						completed: false,
						disabled: false,
						name: "仓",
						imageUrl: "https://www.xiaomicang.com/static/cang3_active.png",
						completedImageUrl: "https://www.xiaomicang.com/static/cang3.png"
					},
				], // 任务列表
				shuffledTasks: [], // 随机排列后的任务列表
				canDraw: false, // 是否可以抽奖
				lotteryResult: null, // 抽奖结果
				lotteryList: [], // 抽奖结果
			};
		},
		created() {
			this.shuffleTasks(); // 页面加载时随机排列按钮
		},
		computed: {
			isLogin() {
				return sheep.$store('user').isLogin; // 确保 sheep.$store 返回响应式数据
			},
		},
		onShow() {
			// 正确访问 computed 属性
			if (!this.isLogin) {
				showAuthModal('accountLogin'); // 假设 showAuthModal 是你的方法
				console.log('用户未登录');
			}
		},
		// watch: {
		// 	isLogin(newVal) {
		// 		if (newVal) {
		// 			console.log("检测到用户已登录，加载奖品数据...");
		// 			this.randomPrizes();
		// 		}
		// 	}
		// },
		methods: {
			toHome() {
				console.log('11');
				uni.switchTab({
					url: '/pages/index/index'
				})
			},
			async randomPrizes() {
				try {
					const isLogin = sheep.$store('user')?.isLogin;
					if (!isLogin) {
						showAuthModal('accountLogin');
						// 如果未登录，提示用户登录
						uni.showToast({
							title: "请先登录",
							icon: "none",
						});

						return;
					}
					const res = await sheep.$api.app.randomPrizes();
					console.log(JSON.stringify(res, null, 2)); // 美化输出
					if (res.code === 1) {
						// 将奖品数据保存到 lotteryList 中
						this.lotteryList.push({
							id: res.data.id,
							name: res.data.name,
							imageUrl: res.data.image,
							is_winner: 1
						});
						// this.lotteryList = res.data.map(item => ({
						// 	id: item.id,
						// 	name: item.name,
						// 	imageUrl: item.image,
						// 	is_winner: item.is_winner
						// }));
					} else {
						this.lotteryList.is_winner = 0;
						uni.showToast({
							title: "加载礼品失败",
							icon: "none",
						});
					}
				} catch (error) {
					console.error("加载奖品数据失败:", error);
					uni.showToast({
						title: "请求失败，请稍后重试",
						icon: "none",
					});
				}
			},
			// 随机排列任务并确保按钮不重叠
			shuffleTasks() {
				const buttons = this.tasks.map(task => ({
					...task,
					disabled: false,
					completed: false,
				}));
				let occupiedPositions = [];

				buttons.forEach(task => {
					let position = this.getRandomPosition(occupiedPositions);
					task.top = position.top;
					task.left = position.left;
					occupiedPositions.push(position);
				});

				this.shuffledTasks = buttons;
			},

			// 点击红包开始抽奖
			openLottery: async function() {
				try {
					const userInfo = await sheep.$store('user').getInfo();
					console.log(userInfo);
					this.canDraw = false;

					// 先执行 this.randomPrizes，并等待它完成
					await this.randomPrizes();

					// 再执行抽奖逻辑
					this.startLottery();
				} catch (error) {
					console.error('获取用户信息失败:', error);
				}
			},


			// 抽奖逻辑
			startLottery() {
				console.log(this.lotteryList.length);
				if (this.lotteryList.length === 0) {
					uni.showToast({
						title: "暂无奖品可抽取",
						icon: "none",
					});
					return;
				}

				// 模拟抽奖结果
				this.lotteryResult = this.lotteryList.filter(prize => prize.is_winner === 1);

			},

			// 关闭抽奖结果弹窗
			closeLotteryResult(name) {
				this.lotteryResult = null;
				uni.showToast({
					title: "抽奖结束！",
					icon: "success",
				});
				if (!name || name === '谢谢惠顾') {
				    uni.switchTab({
				    	url: '/pages/index/index'
				    })
				}else{
					uni.redirectTo({
					    url: "/pages/user/lotteryRecords/list"
					})
				}

			},
			// 生成一个随机的位置，避免重叠
			getRandomPosition(occupiedPositions) {
				const imageHeight = 120; // 图片高度
				const imageWidth = 100; // 图片宽度
				const screenHeight = uni.getSystemInfoSync().windowHeight; // 屏幕高度
				const screenWidth = uni.getSystemInfoSync().windowWidth; // 屏幕宽度
				const maxTop = screenHeight / 2 - imageHeight;
				const minDistance = 100; // 最小间距
				let position;
				let validPosition = false;

				while (!validPosition) {
					validPosition = true;
					position = {
						top: Math.random() * maxTop, // 垂直位置限制在上半部分
						left: Math.random() * (screenWidth - imageWidth), // 水平随机
					};

					// 检查与已有位置是否冲突
					for (let pos of occupiedPositions) {
						const distance = Math.sqrt(
							Math.pow(position.top - pos.top, 2) + Math.pow(position.left - pos.left, 2)
						);
						if (distance < minDistance) {
							validPosition = false;
							break;
						}
					}
				}

				return position;
			},

			// 获取按钮的随机位置样式
			getButtonStyle(index) {
				return {
					position: 'absolute',
					top: `${this.shuffledTasks[index].top}px`,
					left: `${this.shuffledTasks[index].left}px`,
				};
			},

			// 点击任务按钮
			completeTask(index) {
				const isLogin = sheep.$store('user')?.isLogin;
				if (!isLogin) {
					showAuthModal('accountLogin');
					// 如果未登录，提示用户登录
					uni.showToast({
						title: "请先登录",
						icon: "none",
					});

					return;
				}
				const task = this.shuffledTasks[index];

				if (!task.completed && task.id === this.getNextTaskId()) {
					// 标记任务为完成
					task.completed = true;

					// 替换当前图片为完成后的图片
					task.imageUrl = task.completedImageUrl;

					// 动态提示任务完成内容
					uni.showToast({
						title: `任务 “${task.name}” 已完成！`,
						icon: "success",
						duration: 300,
					});

					// 检查任务是否全部完成
					this.checkTasks();
				} else if (task.completed) {
					uni.showToast({
						title: `任务 “${task.name}” 已完成！`,
						icon: "none",
						duration: 300,
					});
				} else {
					uni.showToast({
						title: `请按顺序点击图片！`,
						icon: "none",
					});
				}
			},

			// 获取下一个需要点击的任务ID
			getNextTaskId() {
				for (let i = 0; i < this.shuffledTasks.length; i++) {
					if (!this.shuffledTasks[i].completed) {
						return this.shuffledTasks[i].id;
					}
				}
				return -1; // 所有任务已完成
			},

			// 检查任务是否全部完成
			checkTasks() {
				this.canDraw = this.shuffledTasks.every((task) => task.completed); // 全部完成才允许抽奖

			},

			// 打开抽奖弹窗
			openLotteryModal() {
				// 隐藏抽奖按钮
				this.canDraw = false;
			},


			// 关闭抽奖弹窗并禁用按钮
			closeLotteryModal() {
				// 禁用所有按钮
				this.shuffledTasks.forEach(task => {
					task.disabled = true;
				});

				// 重新排列按钮
				this.shuffleTasks();

				// 清除抽奖结果并恢复按钮状态
				this.lotteryResult = null;
			}
		},
	};
</script>

<style lang="scss" scoped>
	.container {
		position: relative;
		height: 100vh;
		width: 100%;
		overflow: hidden;
	}

	.bg-img {
		width: 100%;
		height: 100vh;
		// object-fit: cover; /* 图片适配容器，防止拉伸 */
		position: absolute;
		top: 0;
		left: 0;
		z-index: -1;
		object-fit: contain;
	}

	.back {
		width: 30rpx;
		height: 50rpx;
		position: absolute;
		top: 6%;
		left: 4%;
		z-index: 9999;
	}

	.title {
		font-size: 36rpx;
		font-weight: bold;
		text-align: center;
		padding-top: 180rpx;
		color: #00ad51;
	}

	.task-buttons {
		position: relative;
		margin-top: 100rpx;
	}

	.task-button {
		width: 200rpx;
		height: 88rpx;
		line-height: 88rpx;
		text-align: center;
		font-size: 28rpx;
		border-radius: 10rpx;
		background-color: #eee;
		color: #333;
		margin-bottom: 20rpx;
	}

	.task-image {
		width: 130rpx;
		height: 130rpx;
		position: absolute;
		/* 必须使用绝对定位 */
		transition: all 0.3s ease;
		/* 添加过渡效果 */
	}


	.task-button.completed {
		background-color: #4caf50;
		color: #fff;
	}

	.task-button.disabled {
		background-color: #d3d3d3;
		color: #9e9e9e;
		cursor: not-allowed;
	}

	.lottery-button {
		width: 100%;
		height: 88rpx;
		background-color: #007aff;
		color: #fff;
		font-size: 28rpx;
		text-align: center;
		line-height: 88rpx;
		border-radius: 10rpx;
		border: none;
		margin-top: 20rpx;
	}

	.red {
		width: 350rpx;
		z-index: 4;
	}

	/* Modal Style */
	.modal {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.banner {
		width: 600rpx;
		height: 600rpx;
		margin-bottom: 110rpx;
		z-index: -1;

	}

	.modal-content {
		width: 80%;
		padding: 40rpx;
		background-color: white;
		border-radius: 10rpx;
		text-align: center;
	}

	.modal-title {
		font-size: 30rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
	}

	.modal-body {
		font-size: 28rpx;
		margin-bottom: 30rpx;
	}

	.close-button {
		width: 270rpx;
		height: 75rpx;
		background-color: #F95462;
		/* 按钮背景颜色 */
		color: white;
		/* 文字颜色 */
		font-size: 30rpx;
		/* padding: 10rpx 30rpx; */
		border: none;
		border-radius: 60rpx;
		cursor: pointer;
		/* 鼠标悬停时的指针样式 */
		align-items: center;
		line-height: 75rpx;
		margin-top: 20rpx;
	}

	/* 抽奖弹窗 */
	.result-modal {
		position: fixed;
		top: 45%;
		left: 50%;
		transform: translate(-50%, -50%);
		width: 600rpx;
		height: auto;
		/* 高度自适应内容 */
		text-align: center;
		/* padding-top: 100rpx; */
	}

	.result-content {
		padding: 40rpx;
	}

	.result-image {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 20rpx;
	}

	.result-text-wrapper {
		margin-top: 80rpx;
		display: flex;
		align-items: center;
		/* 垂直居中 */
		justify-content: center;
		/* 如果需要水平居中 */
	}

	.result-text {
		font-size: 32rpx;
		margin-bottom: 20rpx;
		color: #803E38;
	}

	.result {
		font-size: 32rpx;
		margin-bottom: 20rpx;
		color: #F7534A;
		margin-left: 10rpx;
	}

	.result-bottom {
		font-size: 28rpx;
		font-weight: bolder;
	}

	.close {
		position: fixed;
		top: 70%;
		width: 80rpx;
		height: 80rpx;
	}

	.login-btn-start {
		width: 4.9375rem;
		height: 1.75rem;
		line-height: normal;
		background: linear-gradient(90deg, #28a745, #218838);
		/* 绿色渐变背景 */
		border-radius: 0.875rem;
		font-size: 0.8125rem;
		font-weight: 500;
		color: #fff;
		/* 字体颜色为白色 */
		position: relative;
		/* 添加相对定位以支持 ::after 的绝对定位 */
		text-align: center;
		/* 居中对齐文本 */
		display: flex;
		/* 让文本垂直居中 */
		justify-content: center;
		align-items: center;

		&::after {
			content: '';
			display: block;
			width: 100%;
			height: 2px;
			z-index: 1;
			position: absolute;
			left: 0;
			bottom: -10px;
			/* 调整下边距 */
			background: #28a745;
			/* 使用主绿色 */
			pointer-events: none;
			border-radius: 1px;
			/* 添加轻微圆角 */
		}

		&:hover {
			background: linear-gradient(90deg, #218838, #1e7e34);
			/* 添加悬停效果的更深绿色渐变 */
		}
	}

	.bg-img-mi {
		position: absolute;
		width: 541rpx;
		height: 410rpx;
		left: 50%;
		transform: translateX(-50%);
		bottom: 180rpx;
	}
</style>